package myUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * <p>
 * �ַ������
 * </p>
 * 
 * <p>
 * Copyright: 2009 . All rights reserved.
 * </p>
 * <p>
 * Company: Zsoft
 * </p>
 * <p>
 * CreateDate:2009-4-28
 * </p>
 * 
 * @author young
 * @history �����ĵ���Mender:young��Date:2009-4-28��
 */
public class StringUtil {

	/**
	 * ��������λ��ת������
	 */
	private static final int GB_SP_DIFF = 160;

	/**
	 * ��Ź��һ�����ֲ�ͬ��������ʼ��λ��
	 */
	private static final int[] secPosvalueList = { 1601, 1637, 1833, 2078,
			2274, 2302, 2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730,
			3858, 4027, 4086, 4390, 4558, 4684, 4925, 5249, 5600 };

	/**
	 * ��Ź��һ�����ֲ�ͬ��������ʼ��λ���Ӧ����
	 */
	private static final char[] firstLetter = { 'a', 'b', 'c', 'd', 'e', 'f',
			'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
			'w', 'x', 'y', 'z' };

	/**
	 * ��ȡһ���ַ��ƴ���� ��"�й��̾�"--->sgsj
	 * 
	 * @param oriStr
	 *            �ַ�
	 * @return ƴ������ĸ
	 */
	public static String getFirstLetter(String oriStr) {
		String str = oriStr;
		if (isNullOrEmpty(str)) {
			return "";
		}
		StringBuffer buffer = new StringBuffer();
		char ch;
		char[] temp;
		for (int i = 0; i < str.length(); i++) {
			// ���δ���str��ÿ���ַ�
			ch = str.charAt(i);
			temp = new char[] { ch };
			byte[] uniCode = new String(temp).getBytes();
			if (uniCode[0] < 128 && uniCode[0] > 0) {
				// �Ǻ���
				buffer.append(temp);
			} else {
				buffer.append(convert(uniCode));
			}
		}
		return buffer.toString();
	}

	/**
	 * ��ȡһ���ַ��ƴ���������ĸ ��"�й��̾�"--->s
	 * 
	 * @param oriStr
	 *            �ַ�
	 * @return ƴ������ĸ
	 */
	public static String getFirstOneLetter(String oriStr) {
		String str = oriStr;
		if (isNullOrEmpty(str)) {
			return "";
		}
		char ch;
		char[] temp;
		for (int i = 0; i < str.length(); i++) {
			// ����str�еĵ�һ���ַ�
			ch = str.charAt(i);
			temp = new char[] { ch };
			byte[] uniCode = new String(temp).getBytes();
			if (uniCode[0] < 128 && uniCode[0] > 0) {
				// �Ǻ���ֱ�ӷ���
				return String.valueOf(ch);
			} else {
				return String.valueOf(convert(uniCode));
			}
		}
		return null;

	}

	/**
	 * ��ȡһ�����ֵ�ƴ������ĸ�� GB�������ֽڷֱ��ȥ160��ת����10��������ϾͿ��Եõ���λ��
	 * ���纺�֡��㡱��GB����0xC4/0xE3���ֱ��ȥ0xA0��160������0x24/0x43
	 * 0x24ת��10���ƾ���36��0x43��67����ô�����λ�����3667���ڶ��ձ��ж���Ϊ��n��
	 */
	private static char convert(byte[] bytes) {
		char result = '-';
		int secPosvalue = 0;
		int i;
		for (i = 0; i < bytes.length; i++) {
			bytes[i] -= GB_SP_DIFF;
		}
		secPosvalue = bytes[0] * 100 + bytes[1];
		for (i = 0; i < 23; i++) {
			if (secPosvalue >= secPosvalueList[i]
					&& secPosvalue < secPosvalueList[i + 1]) {
				result = firstLetter[i];
				break;
			}
		}
		return result;
	}

	/**
	 * ��ȡ �ַ��Ƿ��
	 * 
	 * @param string
	 *            �ַ�
	 * @return �ַ��Ƿ��
	 */
	public static boolean isNullOrEmpty(String string) {
		if (string == null || string.equals(""))
			return true;
		else {
			if (string.trim().equals(""))
				return true;
		}
		return false;
	}

	/**
	 * �ַ�s1�Ƿ����s2
	 * 
	 * @param s1
	 *            �ַ�1
	 * @param s2
	 *            �ַ�2
	 * @param isIgnoredCase
	 *            �Ƿ���Դ�Сд
	 * @return �Ƿ����
	 */
	public static boolean isEqual(String s1, String s2, boolean isIgnoredCase) {

		if (s1 == null || s2 == null)
			return false;

		if (isIgnoredCase)
			return s1.equalsIgnoreCase(s2);
		else
			return s1.equals(s2);

	}
	
	/**
	 * �ַ�s1�Ƿ����s2
	 * 
	 * @param s1
	 *            �ַ�1
	 * @param s2
	 *            �ַ�2
	 * @param isIgnoredCase
	 *            �Ƿ���Դ�Сд
	 * @param flag
	 *            true��ʾ������false��ʾ������
	 * @return �Ƿ����
	 */
	public static boolean isEqual(boolean isIgnoredCase,boolean flag,String s1, String... s2) {

		if (s1 == null || s2 == null)
			return false;
		boolean result = false;
		for(String t_s2:s2){
			if (isIgnoredCase){
				if(flag){
					result = result||s1.equalsIgnoreCase(t_s2);
				}else{
					result = result&&s1.equalsIgnoreCase(t_s2);
				}
			}
			else{
				if(flag){
					result = result||s1.equals(t_s2);
				}else{
					result = result&&s1.equals(t_s2);
				}
			}
		}
		return result;
	}

	/**
	 * �ַ�s1�Ƿ��s2
	 * 
	 * @param s1
	 *            �ַ�s1
	 * @param s2
	 *            �ַ�s2
	 * @return �Ƿ��
	 */
	public static boolean containsString(String s1, String s2) {
		if (s2 == null) {
			return true;
		}

		if (s1 == null) {
			return false;
		}

		return s1.contains(s2);
	}

	/**
	 * �ַ�s1�Ƿ��s2
	 * 
	 * @param s1
	 *            �ַ�s1
	 * @param s2
	 *            �ַ�s2
	 * @param isIgnoredCase
	 *            �Ƿ���Դ�Сд
	 * @return
	 */
	public static boolean containsString(String s1, String s2,
			boolean isIgnoredCase) {
		if (s2 == null) {
			return true;
		}

		if (s1 == null) {
			return false;
		}

		if (isIgnoredCase) {
			return s1.toUpperCase().contains(s2.toUpperCase());
		} else {
			return s1.contains(s2);
		}
	}

	/**
	 * ��Hashtable������ת����key:value��ʽ���ַ�
	 * 
	 * @param hashtable
	 * @return
	 * @since 1.1
	 */
	public static String Hashtable2String(Hashtable<String, String> hashtable) {
		StringBuffer buffer = new StringBuffer();
		if (hashtable != null && !hashtable.isEmpty()) {

			Enumeration<String> keys = hashtable.keys();
			while (keys.hasMoreElements()) {
				String key = keys.nextElement();
				String value = hashtable.get(key);
				buffer.append(String.format("%s:%s\n", key, value));
			}

		}
		return buffer.toString();
	}

	/**
	 * ��key:value��ʽ���ַ�����ת����Hashtable
	 * 
	 * @param str
	 * @return
	 * @since 1.1
	 */
	public static Hashtable<String, String> String2Hashtable(String str) {
		Hashtable<String, String> result = new Hashtable<String, String>();

		/** ��key:value��ʽ���ַ�ת����Hashtable */
		if (!StringUtil.isNullOrEmpty(str)) {
			String[] items = str.split("\n");
			for (String item : items) {
				if (!StringUtil.isNullOrEmpty(item)) {
					int index = item.indexOf(':');
					if (index > 0) {
						String key = item.substring(0, index - 1);
						String value = item.substring(index + 1);
						result.put(key, value);
					}
				}
			}
		}

		return result;
	}

	/**
	 * ��String[]������ת�����ö��ŷָ����ַ�
	 * 
	 * @param array
	 * @return
	 * @since 1.1
	 */
	public static String Array2String(String[] array) {
		StringBuffer buffer = new StringBuffer();
		if (array != null && array.length > 0) {
			for (int i = 0; i < array.length; i++) {
				buffer.append(array[i]);
				if (i < array.length - 1) {
					buffer.append(",");
				}
			}

		}
		return buffer.toString();
	}

	/**
	 * ��֤target���Ƿ��keywords����������
	 * 
	 * @param target
	 * @param keywords
	 * @return
	 */
	public static boolean containAll(Set<String> target, Set<String> keywords) {

		if (target == null || target.isEmpty()) {
			return false;
		}

		Map<String, Boolean> map = new HashMap<String, Boolean>();
		for (Iterator<String> it = keywords.iterator(); it.hasNext();) {
			map.put(it.next(), Boolean.FALSE);
		}

		for (Iterator<String> tarItem = target.iterator(); tarItem.hasNext();) {
			String tagStrItem = tarItem.next();
			for (Iterator<String> expItem = keywords.iterator(); expItem
					.hasNext();) {
				String expStrItem = expItem.next();
				if (!isNullOrEmpty(tagStrItem)
						&& tagStrItem.contains(expStrItem)) {
					map.put(expStrItem, Boolean.TRUE);
				}
			}
		}

		Collection<Boolean> coll = map.values();
		for (Boolean item : coll) {
			if (Boolean.FALSE.equals(item)) {
				return false;
			}
		}

		return true;
	}

	/**
	 * ��֤target���Ƿ��keywords���������� (���Դ�Сд)
	 * 
	 * @param target
	 * @param keywords
	 * @return
	 */
	public static boolean containAllIgnoreCase(Set<String> target,
			Set<String> keywords) {

		if (target == null || target.isEmpty()) {
			return false;
		}

		Map<String, Boolean> map = new HashMap<String, Boolean>();
		for (Iterator<String> it = keywords.iterator(); it.hasNext();) {
			map.put(it.next(), Boolean.FALSE);
		}

		for (Iterator<String> tarItem = target.iterator(); tarItem.hasNext();) {
			String tagStrItem = tarItem.next().trim();
			for (Iterator<String> expItem = keywords.iterator(); expItem
					.hasNext();) {
				String expStrItem = expItem.next().trim();
				if (!isNullOrEmpty(tagStrItem)
						&& tagStrItem.toLowerCase().trim()
								.contains(expStrItem.toLowerCase().trim())) {
					map.put(expStrItem, Boolean.TRUE);
				}
			}
		}

		Collection<Boolean> coll = map.values();
		for (Boolean item : coll) {
			if (Boolean.FALSE.equals(item)) {
				return false;
			}
		}

		return true;
	}

	/**
	 * ��ȡGetterSetter�ֶ���� ���� XM_SJ --> XmSj
	 * 
	 * @param fieldName
	 * @return
	 */
	public static String getGetterSetterName(String fieldName) {
		fieldName = fieldName.toLowerCase();
		while (fieldName.contains("_")) {
			int index = fieldName.indexOf('_');
			fieldName = fieldName.substring(0, index)
					+ fieldName.substring(index + 1, index + 2).toUpperCase()
					+ fieldName.substring(index + 2);
		}
		String getterSetterName = Character.toUpperCase(fieldName.charAt(0))
				+ fieldName.substring(1);

		return getterSetterName;
	}

	/**
	 * ����ĸת��Ϊ��д
	 * 
	 * @param string
	 * @return
	 */
	public static String firstLetterToUpper(String string) {
		if (StringUtil.isNullOrEmpty(string))
			return "";

		return string.substring(0, 1).toUpperCase() + string.substring(1);
	}

	/**
	 * ����ĸת��ΪСд
	 * 
	 * @param string
	 * @return
	 */
	public static String firstLetterToLower(String string) {
		if (StringUtil.isNullOrEmpty(string))
			return "";

		return string.substring(0, 1).toLowerCase() + string.substring(1);
	}

	/**
	 * �Ƿ����ֿ�ѧ���㷨�����,�жϵ�����Ϊ����,���ҳ��Ȳ�С��ʮ��λ
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isScientificNotationNumeric(String str) {
		if (!StringUtil.isNullOrEmpty(str) && str.length() >= 12) {
			if (str.matches("\\d*")) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * ȥ���ո���õĺ���
	 * 
	 */
	public static String trim(String keyword) {
		if (!StringUtil.isNullOrEmpty(keyword)) {
			keyword = keyword.trim();
		}
		return keyword;

	}

	/**
	 * �ַ�ת������
	 * 
	 * @param dateStr
	 * @param formatStr
	 * @return
	 */
	public static Date StringToDate(String dateStr, String formatStr) {
		if (isNullOrEmpty(formatStr))
			formatStr = "yyyy-MM-dd";
		DateFormat dd = new SimpleDateFormat(formatStr);
		Date date = null;
		try {
			date = dd.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * ���ذٷֱȸ�ʽ %
	 * 
	 * @param i
	 * @return
	 */
	public static String getPercentFormat(String word)
	{
		BigDecimal result = null;
		try
        {
			result = new BigDecimal(word);
        }
        catch (Exception e)
        {
	        
        }
		if(result != null)
		{
			DecimalFormat df = new DecimalFormat("#.##%");	
			return df.format(result.setScale(4,   BigDecimal.ROUND_HALF_UP).doubleValue());
		}
		
		return word;
	}
	
	/**
	 * ���ذٷֱȸ�ʽ %
	 * 
	 * @param i
	 * @return
	 */
	public static String getPercentFormat(double word)
	{
		return getPercentFormat(""+word);
	}
	
	/**
	 * �ָ��ַ�
	 * @param value
	 * @param splitSign
	 * @return
	 */
	public static List<String> getSplitString(String value,String... splitSign){
		List<String> resultList=new ArrayList<String>();
		String firstSign = splitSign[0];
		for(String sign:splitSign){
			value = value.replaceAll(sign, firstSign);
		}
		String[] results = value.split(firstSign);
		if(results!=null){
			for(String t_value:results){
				if(!StringUtil.isNullOrEmpty(t_value)&&!StringUtil.isNullOrEmpty(t_value.trim())){
					resultList.add(t_value);
				}
			}
		}
		return resultList;
	}
	
	/**
	 * ת���ַ���������ʽ�������ַ�
	 * @return
	 */
	public static String convertRegexToken(String value){
		if(!StringUtil.isNullOrEmpty(value)){
			value = value.replace(".", "\\.");
			value = value.replace("$", "\\$");
			value = value.replace("^", "\\^");
			value = value.replace("{", "\\{");
			value = value.replace("[", "\\[");
			value = value.replace("(", "\\(");
			value = value.replace("|", "\\|");
			value = value.replace(")", "\\)");
			value = value.replace("*", "\\*");
			value = value.replace("+", "\\+");
			value = value.replace("?", "\\?");
		}
		return value;
	}
	
	/**
	 * ת���ַ���������ʽ�������ַ�
	 * @return
	 */
	public static String convertRegexToken2(String value){
		if(!StringUtil.isNullOrEmpty(value)){
			value = value.replace("\\", "\\u005C");
			value = value.replace(".", "\\u002E");
			value = value.replace("$", "\\u0024");
			value = value.replace("^", "\\u005E");
			value = value.replace("{", "\\u007B");
			value = value.replace("[", "\\u005B");
			value = value.replace("(", "\\u0028");
			value = value.replace("|", "\\u007C");
			value = value.replace(")", "\\u0029");
			value = value.replace("*", "\\u002A");
			value = value.replace("+", "\\u002B");
			value = value.replace("?", "\\u003F");
		}
		return value;
	}
	
	public static boolean isNumeric(String str)
    {
        if(str == null)
            return false;
        int sz = str.length();
        for(int i = 0; i < sz; i++)
            if(!Character.isDigit(str.charAt(i)))
                return false;

        return true;
    }
	
	/**
	 * ȫ������ת�������
	 * @param SBCString ȫ�����ִ�
	 * @return
	 */
	public static String SBC2DBC(String SBCString) 
	{
		 if(SBCString == null){
		    return null;
		 }
		 StringBuffer DBCString = new StringBuffer ("");
		 try {
		    byte[] bytes = null;
		    for (int i = 0; i < SBCString.length (); i++) 
		    {
		    	String temp = SBCString.substring (i , i + 1);
		    	boolean isContainLetters = Pattern.matches ("[0-9a-zA-Z]" , temp);
		    	if (!isContainLetters) 
		    	{
		    		bytes = temp.getBytes ("unicode");
		    		if (bytes[2] == -1) 
		    		{
		    			bytes[3] = (byte) (bytes[3] + 32);
		    			bytes[2] = 0;
		    		}
		    		DBCString.append (new String (bytes , "unicode"));
		    	}else{
		    		DBCString.append (temp);
		    	}
		    }
		 } catch (UnsupportedEncodingException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace ();
		 }
		 return DBCString.toString ();
	}
	
	public static void main(String[] args)
    {
    }
}
